<?php
namespace app\user\controller;
use app\common\controller\HomeBase;

use app\common\model\MessageRead;
use app\common\model\PaymentAccount;
use app\common\model\Message as Model;
use think\captcha\facade\Captcha;


class Message extends HomeBase
{
    protected $model;
    protected $uid;

    public function initialize()
    {
        $this->uid=cacheUserid();
        if(!$this->uid){
            $this->redirect(__url('user/login/index'));
        }

        parent::initialize();
        $this->model = new Model();
    }
    public function index()
    {

        return view();
    }
    public function messages(){
        $uid = cacheUserid();
        if (!$uid) {
            return json(['code' => 0, 'msg' => '没有登录', 'data' => []]);
        }
        $params = $this->params;
        $page = $params['pageIndex'];
        $limit = $params['pageSize'];

        if (isset($params['page'])) {
            $page = $params['page'];
        }
        $where[]=['type','=',$params['type']];
        $where[] = ['to_uid','in',[0,$uid]];
        $count = $this->model->where($where)->count();
        $list = $this->model
            ->where($where)
            ->order('id', 'desc')
            ->page($page, $limit)
            ->select();
        if($list){
            $list=$list->toArray();
            $ids=array_column($list,'id');
            $hasMsgIds=(new MessageRead())->where('user_id',$uid)
                ->whereIn('message_id',$ids)->column('id','message_id');
            foreach ($list as &$v){
                $v['created_at']=strtotime($v['create_time']);
                $v['has_read']=0;
                if(isset($hasMsgIds[$v['id']])){
                    $v['has_read']=1;
                }
            }
        }
        return json(array(
            'code' => 1,
            'msg' => '获取成功',
            'data' => ['list' => $list, 'pager' => [
                'pageSize' => $limit,
                'pageIndex' => $page,
                'count' => $count
            ]],
        ));
    }
    public function read($id)
    {
        $uid = cacheUserid();
        if (!$uid) {
            return json(['code' => 0, 'msg' => '没有登录', 'data' => []]);
        }
        $messdata['user_id'] = $uid;
        $messdata['message_id']  = $id;

        $item            = (new MessageRead())->where($messdata)->find();
        if ($item) {
            return success('');
        } else {
            $item=new MessageRead();
            $item->save($messdata);
            return success('');
        }
    }

}
